package com.guodi.map.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.*;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.core.tool.utils.StringUtil;
import com.guodi.map.constant.MapConst;
import com.guodi.map.dto.MapLayerDTO;
import com.guodi.map.entity.MapLayer;
import com.guodi.map.entity.MapProjectDir;
import com.guodi.map.service.*;
import com.guodi.map.utils.RecursionUtil;
import com.guodi.map.utils.VerificationUtil;
import com.guodi.map.vo.ApiMapLayer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//import com.guodi.redis.service.IRedisDictService;


/**
 * @描述：地图图层表控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-11
 */
@Validated
@RestController
@RequestMapping("/MapLayer")
@Api(value = "API - MapLayerController", tags = "地图图层表")
public class MapLayerController extends BaseController {

    @Autowired
    private IMapLayerService mapLayerService;
    //    @Autowired
//    private IRedisDictService iRedisDictService;
    @Resource
    private IMapProjectDirService mapProjectDirService;
    @Resource
    private IMapCommonService commonService;
    @Autowired
    public IMapDataSourceService dataSourceService;
    @Autowired
    private IGISServiceParser ogcServiceParser;

    private boolean isServerFolder = false;

    /**
     * @描述: 根据当前用户查询已经授权的机构
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/2/11 10:48
     **/
    @PostMapping("/listOrgByUser")
    @ApiOperation(value = "根据当前用户查询已授权的机构")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resourceId", value = "资源目录ID", required = true, dataType = "string", paramType = "query"),
    })
    public R listOrgByUser(String resourceId) {
        //返回根目录--去除地图资源授权后
        List<MapLayer> mapLayers = mapLayerService.listByOrg(null);
        return R.data(mapLayers);
    }

    /**
     * @描述: 根据实体属性分页查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "parentId", required = true, dataType = "string", paramType = "query")
    })
    public R listByEntity() {
        PageData pd = new PageData(this.getRequest());
        List<MapLayer> dataList = mapLayerService.listByEntity(pd);
        dataList = mapLayerService.getServiceAndLayer(dataList);
        List<MapLayerDTO> result = new ArrayList<>();
        for (MapLayer mapLayer : dataList) {
            MapLayerDTO mapLayerDTO = new MapLayerDTO();
            BeanUtils.copyProperties(mapLayer, mapLayerDTO);
            result.add(mapLayerDTO);
        }
        return R.data(RecursionUtil.buildLayerDTOTree(result));
    }

    /**
     * @作者: 林楷 2021/5/25
     * @描述: 根据父节点ID查新子节点列表
     * @参数: null
     * @返回: null
     */
    @PostMapping("/listByParentId")
    @ApiOperation(value = " 根据实体属性查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "parentId", required = true, dataType = "string", paramType = "query")
    })
    public R listByParentId(String parentId) {
        List<MapLayer> dataList = mapLayerService.listByParentId(parentId);
        return R.data(dataList);
    }

    /**
     * @描述:根据实体属性查询列表(懒加载)
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2021/1/13 11:29
     **/
    @PostMapping("/listLazyByEntity")
    @ApiOperation(value = " 根据实体属性查询列表(懒加载)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "parentId", required = true, dataType = "string", paramType = "query")
    })
    public R listLazyByEntity() {
        PageData pd = new PageData(this.getRequest());
        List<MapLayer> list = mapLayerService.listLazyByEntity(pd);
        return R.data(list);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if (StringUtils.isBlank(id)) {
            return R.fail("id不能为空");
        }
        MapLayer mapLayer = mapLayerService.getById(id);
        return R.data(mapLayer);
    }

    /**
     * 有图层
     * 多图层的
     * type:3 图层
     * <p>
     * 隐藏图层
     * 隐藏图层的服务有可能有图层
     * type:2 服务
     * 没有图层
     * type:2 服务
     *
     * @描述: 新增图层
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增图层")
    public R save(@Valid ApiMapLayer apiMapLayer) {
        try {
            String url = URLDecoder.decode(apiMapLayer.getLayerUrl(), "UTF-8");
            apiMapLayer.setLayerUrl(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        MapLayer mapLayer = new MapLayer();
        BeanUtils.copyProperties(apiMapLayer, mapLayer);
        if (!prepareData(mapLayer, true)) {
            return R.fail("该图层名已经存在,请更换！");
        }
//        final String layerUrl = mapLayer.getLayerUrl();
//        List<MapLayer> resultList =new ArrayList<>();
//        boolean hideLayerFlag =false;
//        String stringByUrl =null;
//        if(!mapLayerService.ogcFlag(layerUrl)){
//            stringByUrl= ReadFileUtil.getStringByUrl(layerUrl + MapConst.URL_SUFFIX);
//            hideLayerFlag = saveHideLayerService(mapLayer, resultList, stringByUrl,false);
//            if(hideLayerFlag){
//                return R.data(resultList.get(0));
//            }
//        }
        Integer sort = commonService.getMaxSort(mapLayer.getParentId(), "map_layer");

        mapLayer.setSort(sort + 1);
        mapLayer.setId(UuidUtil.get32UUID());
//        fillLayer(mapLayer,stringByUrl);
        mapLayer.setCreateTime(new Date());
        mapLayer.setCreator(getUser().getUserId() + "");
//        mapLayer.setLayerType("2");
        mapLayer.setType("2");
        mapLayerService.saveMaplayer(mapLayer, true);
        return R.data(mapLayer);
    }

    /**
     * @描述: 新增目录
     * @入参:
     * @出参:
     * @作者: 邹艺
     * @日期: 2020-01-02
     **/
    @PostMapping("/saveDir")
    @ApiOperation(value = "新增目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "name", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "parentId", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "orgId", required = true, dataType = "string", paramType = "query")
    })
    public R saveDir() {
        PageData pd = new PageData(this.getRequest());
        //判断当前目录下，目录名称是否存在
        Collection collection = mapLayerService.listByMap(VerificationUtil.verifyMap(pd.getString("alias"), pd.getString("parentId")));
        if (collection.size() > 0) {
            return R.fail("该目录名已经存在,请更换！");
        }
        //排序
        Integer sort = commonService.getMaxSort(pd.getString("parentId"), "map_layer");
        MapLayer mapLayer = new MapLayer();
        mapLayer.setId(UuidUtil.get32UUID());
        mapLayer.setName(pd.getString("name"));
        mapLayer.setAlias(pd.getString("alias"));
        mapLayer.setParentId(pd.getString("parentId"));
        mapLayer.setOrgId(pd.getString("orgId"));
        mapLayer.setType("1");
        mapLayer.setSort(sort + 1);
        mapLayerService.save(mapLayer);
        return R.data(mapLayer.getId());
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    @Transactional(rollbackFor = Exception.class)
    public R update(MapLayer mapLayer) {
        //2023.11.01修改。
        String type = mapLayer.getType();
        if ("1".equals(type)) {
            if (StringUtil.isBlank(mapLayer.getAlias())) {
                return R.fail("请输入目录名称");
            }
            //判断同一个目录下是否有同名的
            LambdaQueryWrapper<MapLayer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MapLayer::getParentId, mapLayer.getParentId());
            queryWrapper.eq(MapLayer::getName, mapLayer.getAlias());
            queryWrapper.ne(MapLayer::getId, mapLayer.getId());
            Integer count = mapLayerService.count(queryWrapper);
            if (count > 0) {
                return R.fail("同级目录下有相同的名称,请修改");
            }
            Integer sort = mapLayer.getSort();
            if (sort == null) {
                sort = 1;
                if (StringUtil.isNotBlank(mapLayer.getParentId())) {
                    sort = mapLayerService.getMaxSortByParentId(mapLayer.getParentId());
                }
            }
            //如果是编辑目录的话
            LambdaUpdateWrapper<MapLayer> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(MapLayer::getName, mapLayer.getAlias());
            updateWrapper.set(MapLayer::getAlias, mapLayer.getAlias());
            updateWrapper.set(MapLayer::getSort, sort);
            updateWrapper.eq(MapLayer::getId, mapLayer.getId());
            Boolean flag = mapLayerService.update(updateWrapper);
            if (flag) {
                MapLayer resultMapLayer = mapLayerService.getById(mapLayer.getId());
                return R.data(resultMapLayer);
            } else {
                return R.success("修改失败");
            }
        }
        try {
            String url = URLDecoder.decode(mapLayer.getLayerUrl(), "UTF-8");
            mapLayer.setLayerUrl(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!prepareData(mapLayer, false)) {
            return R.fail("该图层名已经存在,请更换！");
        }
        // 更新图层名称时，对应更新专题服务关联的图层名称
        if (StringUtils.isNotBlank(mapLayer.getName())) {
            Map map = new HashMap();
            map.put("layer_id", mapLayer.getId());
            List<MapProjectDir> mapProjectDirList = (List<MapProjectDir>) mapProjectDirService.listByMap(map);
            if (mapProjectDirList.size() > 0) {
                mapProjectDirService.updateNameByIds(mapProjectDirList.stream().map(x -> x.getId()).collect(Collectors.toList()), mapLayer.getName());
            }
        }
//        if(changeUrl(mapLayer)){
//           return R.data(mapLayer);
//        }
        mapLayerService.updateById(mapLayer);
        mapLayer.setAlias(mapLayer.getName());
        mapLayerService.syncLayerName(Arrays.asList(mapLayer));
        return R.data(mapLayer);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除目录、图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "string", paramType = "query")
    })
    public R delete(String id) {
        //查看该图层是否被关联
        /*Map map = new HashMap();
        map.put("layer_id",id);
        List<MapProjectDir> mapProjectDirList = (List<MapProjectDir>)mapProjectDirService.listByMap(map);
        if(mapProjectDirList.size() > 0){
            return R.fail(StatusCode.ERROR_CODE_40005,"该图层已在专题服务图层名为"+mapProjectDirList.get(0).getName()+"关联,请检查！");
        }
        List<MapFunctionDir> mapFunctionDirList = (List<MapFunctionDir>)mapFunctionDirService.listByMap(map);
        if(mapFunctionDirList.size() > 0){
            return R.fail(StatusCode.ERROR_CODE_40005,"该图层已在功能模块图层名为"+mapFunctionDirList.get(0).getName()+"关联,请检查！");
        }*/
        // 删除图层信息
        mapLayerService.deleteById(id.split(","));
        return R.data(null);
    }

    /**
     * @描述: 根据图层url、表名获取要素类型
     * @入参:
     * @出参:
     * @作者: 彭辉
     * @日期: 2020/10/29 15:39
     **/
    @PostMapping("/getFeatureTypeByUrlAndTableId")
    @ApiOperation(value = "根据图层url、表名获取要素类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "layerUrl", value = "图层url", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layerTable", value = "图层tableId", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "authKey", value = "服务授权", required = false, dataType = "string", paramType = "query")
    })
    public R getFeatureTypeByUrlAndTable(String layerUrl, String layerTable, String authKey) {
        // 初始化查询参数
        Map<String, String> params = new HashMap();
        params.put("f", "pjson");
        if (StringUtils.isNotBlank(authKey)) {
            // 服务来源与基础信息平台
            JSONObject authKeyJson = JSONObject.parseObject(authKey);
            params.put(authKeyJson.getString("key"), authKeyJson.getString("value"));
        }
        String jsonStr = ReadFileUtil.getStringByUrl(layerUrl + "/" + layerTable, params);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if (jsonObject.containsKey("type") && jsonObject.getString("type").equals("rasterLayer")) {
            return R.data("yslx_grid_2");
        }
        if (StringUtils.isNotBlank(jsonObject.getString("geometryType"))) {
            if (jsonObject.getString("geometryType").equals("esriGeometryPoint") || jsonObject.getString("geometryType").equals("esriGeometryMultipoint")) {
                return R.data("yslx_point");
            } else if (jsonObject.getString("geometryType").equals("esriGeometryPolyline")) {
                return R.data("yslx_polyline");
            } else if (jsonObject.getString("geometryType").equals("esriGeometryPolygon")) {
                return R.data("yslx_polygon");
            }
        }
        return R.data("yslx_grid_2.5");
    }

    /**
     * @描述:根据图层地址加载图表/四至点坐标/图层坐标系
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/27 16:05
     **/
    @PostMapping("/loadLayerTable")
    @ApiOperation(value = "根据图层地址加载图表/四至点坐标/图层坐标系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "layerUrl", value = "图层URL", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "releaseType", value = "发布类型(超图:iserver，arcgis:arcgis)", required = true, dataType = "string", paramType = "query")
    })
    public R loadLayerTable(String layerUrl, String releaseType) {
        //不需要后台去做处理
        if ("iserver".equals(releaseType)) {
            return R.data(null);
        }
        //处理特殊字符导致接口转义问题
        layerUrl = StringEscapeUtils.unescapeXml(layerUrl);
        if (!StringUtils.isNotBlank(releaseType)) {
            return R.fail("请选择发布软件类型！");
        }
        String[] urlArray = layerUrl.split("/");
        if (mapLayerService.ogcFlag(layerUrl)) {
            Map<String, Object> ogcResult = ogcServiceParser.loadLayerTable(layerUrl, releaseType);
            String layerType = mapLayerService.getLayerType(layerUrl, null);
            ogcResult.put("alias", urlArray[urlArray.length - 2]);
            ogcResult.put("layerType", layerType);
            return R.data(ogcResult);
        }
        // 存储图层表名
        List<JSONObject> layerTableList = new ArrayList<JSONObject>();
        Map<String, Object> resultMap = new HashMap<>();
        // 校验服务地址是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(layerUrl);
        JSONObject serviceResult = null;
        if (isExists) {
            if (releaseType.equals(MapConst.MAP_SERVICE_TYPE_ARCGIS) || releaseType.endsWith(MapConst.MAP_SERVICE_TYPE_PLATFORM) || releaseType.endsWith(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM)) {
                // 根据URL地址获取返回的XML文件字符串
                Map<String, String> params = new HashMap();
                params.put("f", "pjson");
                if (releaseType.endsWith(MapConst.MAP_SERVICE_TYPE_PLATFORM)) {
                    if (layerUrl.indexOf("?") != -1) {
                        // 获取数据服务代理授权码，并封装到params参数集合中
                        String[] authInfos = layerUrl.substring(layerUrl.indexOf("?") + 1).split("=");
                        if (authInfos != null && authInfos.length == 2) {
                            params.put(authInfos[0], authInfos[1]);
                        }
                        layerUrl = layerUrl.substring(0, layerUrl.indexOf("?"));
                    }
                } else if (releaseType.endsWith(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM)) {
                    // 国土空间基础信息平台
                    layerUrl = HttpRequester.getParamFromUrl(layerUrl, params);
                }
                // 根据URL地址获取返回的XML文件字符串
                // String jsonStr = ReadFileUtil.getStringByUrl(layerUrl + "?f=pjson");
                String jsonStr = ReadFileUtil.getStringByUrl(layerUrl, params);
                if (StringUtils.isBlank(jsonStr)) {
                    return R.fail("请检查是否为arcgis发布！");
                }
                serviceResult = JSONObject.parseObject(jsonStr);
                String layerType = mapLayerService.getLayerType(layerUrl, serviceResult == null ? new JSONObject() : serviceResult);
                resultMap.put("layerType", layerType);
                String[] split = layerUrl.split("/");
                resultMap.put("alias", split[split.length - 2]);
                JSONObject dataJson = JSONObject.parseObject(jsonStr);
                if (dataJson.containsKey("tileInfo")) {
                    resultMap.put("loadType", "jzfs_tiled");
                } else {
                    resultMap.put("loadType", "jzfs_dynamic");
                }

                if (dataJson.containsKey("layers") && dataJson.get("layers") != null && org.apache.commons.lang3.StringUtils.isNotBlank(dataJson.getString("layers"))) {
                    JSONArray layerArray = dataJson.getJSONArray("layers");
                    for (int i = 0; i < layerArray.size(); i++) {
                        JSONObject layerJson = layerArray.getJSONObject(i);
                        JSONObject newJson = new JSONObject();
                        newJson.put("id", layerJson.getString("id"));
                        newJson.put("name", layerJson.getString("name"));
                        layerTableList.add(newJson);
                    }
                    resultMap.put("layerTableList", layerTableList);
                }
                //邹艺添加2019-08-20 17:09
                if (dataJson.containsKey("initialExtent") && dataJson.get("initialExtent") != null && org.apache.commons.lang3.StringUtils.isNotBlank(dataJson.getString("initialExtent"))) {
                    JSONObject extentObject = dataJson.getJSONObject("initialExtent");
                    String initialExtent = extentObject.getString("xmin") + "," + extentObject.getString("ymin") + "," +
                            extentObject.getString("xmax") + "," + extentObject.getString("ymax");
                    String wkid = extentObject.getJSONObject("spatialReference").getString("wkid");
                    resultMap.put("initialExtent", initialExtent);
                    resultMap.put("wkid", wkid);
                } else {
                    Object layers = dataJson.get("layers");
                    if (layers != null) {
                        JSONArray layerArray = (JSONArray) layers;
                        JSONObject layer = (JSONObject) layerArray.get(0);
                        String wkid = layer.getJSONObject("spatialReference").getString("wkid");
                        resultMap.put("wkid", wkid);
                    }

                }
            } else {
                if (layerUrl.indexOf("wms") != -1 || layerUrl.indexOf("wmts") != -1) {
                    //过滤掉wms与wmts服务
                    return R.data(null);
                }
                String jsonStr = ReadFileUtil.getJsonByUrl(layerUrl + ".json");
                if (StringUtils.isBlank(jsonStr)) {
                    return R.fail("请检查是否为iserver发布！");
                }
                //解析目录
                JSONObject dataJson = JSONObject.parseObject(jsonStr);
                JSONObject extentObject = dataJson.getJSONObject("bounds");
                String epsgCode = dataJson.getJSONObject("prjCoordSys").getString("epsgCode");
                String initialExtent = extentObject.getString("left") + "," + extentObject.getString("bottom") + "," +
                        extentObject.getString("right") + "," + extentObject.getString("top");
                resultMap.put("initialExtent", initialExtent);
                resultMap.put("wkid", epsgCode);
            }
        }
        return R.data(resultMap);
    }

    /**
     * @描述: 根据图层url，发布类型，地图类型生成节点数据(临时)
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/5/6 15:52
     **/
    @PostMapping("/getTemporaryData")
    @ApiOperation(value = "根据图层url，发布类型，地图类型生成节点数据(临时)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "serverUrl", value = "图层url", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "releaseType", value = "发布类型(超图:iserver，arcgis:arcgis,吉奥基础信息平台服务:arcgis-platform，国土空间基础信息平台:arcgis-basis-platform)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layerType", value = "地图类型", required = true, dataType = "string", paramType = "query")
    })
    public R getTemporaryData(String serverUrl, String releaseType, String layerType) {
        List<MapLayer> mapLayerList = new ArrayList<>();
        String spatialReference = "";
        String initialExtent = "";
        if (releaseType.equals(MapConst.MAP_SERVICE_TYPE_ARCGIS)) {
            // arcgis服务
            this.loadLayersByArcgis(serverUrl, "0", mapLayerList, true, true);
            R ajaxResult = loadLayerTable(serverUrl, MapConst.MAP_SERVICE_TYPE_ARCGIS);
            JSONObject dataJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
            initialExtent = dataJson.getString("initialExtent");
            spatialReference = dataJson.getString("wkid");
        } else if (releaseType.equals(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM)) {
            // 国土空间基础信息平台
            this.loadLayersByBasisPlatform(serverUrl, "0", mapLayerList);
            R ajaxResult = loadLayerTable(serverUrl, MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
            JSONObject dataJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
            initialExtent = dataJson.getString("initialExtent");
            spatialReference = dataJson.getString("wkid");
        } else if (releaseType.equals(MapConst.MAP_SERVICE_TYPE_PLATFORM)) {
            // 吉奥基础信息平台服务
            String[] paramArr = serverUrl.substring(serverUrl.indexOf("?") + 1).split("=");
            Map<String, String> params = new HashMap();
            params.put("f", "pjson");
            params.put(paramArr[0], paramArr[1]);
            String newServerUrl = serverUrl.substring(0, serverUrl.indexOf("?"));
            this.loadLayersByArcgisPlatform(newServerUrl, "0", params, mapLayerList);
            R ajaxResult = loadLayerTable(serverUrl, releaseType);
            JSONObject dataJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
            initialExtent = dataJson.getString("initialExtent");
            spatialReference = dataJson.getString("wkid");
        } else {
            this.loadLayersByIserver(serverUrl, mapLayerList);
            //添加iserver服务
            R ajaxResult = loadLayerTable(serverUrl, "iserver");
            if (ajaxResult.getData() != null) {
                JSONObject dataJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
                spatialReference = dataJson.getString("wkid");
                initialExtent = dataJson.getString("initialExtent");
            }
        }
        List<MapLayer> result = new ArrayList<>();
        for (MapLayer mapLayer : mapLayerList) {
            if (mapLayer.getName().indexOf(MapConst.TILE_INFO_STR) > 0) {
                continue;
            }
            // 判断该图层同级下是否已存在
            mapLayer.setType("2");
            mapLayer.setInitialExtent(initialExtent);
            mapLayer.setSpatialReference(spatialReference);
            mapLayer.setLayerType(layerType);
            result.add(mapLayer);
        }
        return R.data(result);
    }

    /**
     * @描述:保存从数据源拖拽过来的图层
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/27 16:06
     **/
    @PostMapping("/saveMoveLayer")
    @ApiOperation(value = "保存从数据源拖拽过来的图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "机构id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "图层目录id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layerData", value = "新增图层数据集", required = true, dataType = "string", paramType = "query")
    })
    public R saveMoveLayer(String orgId, String parentId, String layerData) {
        // 存储要保存的图层集合
        List<MapLayer> mapLayerList = new ArrayList<>();
        // 根据父目录id查询所有图层
        List<MapLayer> layerList = (List<MapLayer>) mapLayerService.listByMap(VerificationUtil.verifyMap(null, parentId));

        // 格式化数据
        JSONObject layerDataJson = JSONObject.parseObject(layerData);
        Map<String, String> iconSkinMap = new HashMap<>();
        if (layerDataJson.containsKey(MapConst.MAP_SERVICE_TYPE_ARCGIS)) {
            JSONArray layerArray = layerDataJson.getJSONArray(MapConst.MAP_SERVICE_TYPE_ARCGIS);
            for (int i = 0; i < layerArray.size(); i++) {
                JSONObject layerJson = layerArray.getJSONObject(i);
                String iconSkin = layerJson.getString("iconSkin");
                String serverUrl = layerJson.getString("serverUrl");
                iconSkinMap.put(serverUrl, iconSkin);
                String layerTable = layerJson.getString("layerTable");
                this.loadLayersByArcgis(serverUrl, layerTable != null ? layerTable : null, mapLayerList, true, false);
            }
        }
        if (layerDataJson.containsKey(MapConst.MAP_SERVICE_TYPE_PLATFORM)) {
            JSONArray layerArray = layerDataJson.getJSONArray(MapConst.MAP_SERVICE_TYPE_PLATFORM);
            for (int i = 0; i < layerArray.size(); i++) {
                JSONObject layerJson = layerArray.getJSONObject(i);
                String serverUrl = layerJson.getString("serverUrl");
                String layerTable = layerJson.getString("layerTable");

                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put(MapConst.MAP_PLATFORM_AUTH_TOKEN, layerJson.getString(MapConst.MAP_PLATFORM_AUTH_TOKEN));
                this.loadLayersByPlatform(serverUrl, layerTable != null ? layerTable : null, paramMap, mapLayerList);
            }
        }
        if (layerDataJson.containsKey(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM)) {
            JSONArray layerArray = layerDataJson.getJSONArray(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
            for (int i = 0; i < layerArray.size(); i++) {
                JSONObject layerJson = layerArray.getJSONObject(i);
                String serverUrl = layerJson.getString("serverUrl");
                String layerTable = layerJson.getString("layerTable");

                this.loadLayersByBasisPlatform(serverUrl, layerTable != null ? layerTable : null, mapLayerList);
            }
        }
        if (layerDataJson.containsKey(MapConst.MAP_SERVICE_TYPE_SUPER_MAP)) {
            JSONArray layerArray = layerDataJson.getJSONArray(MapConst.MAP_SERVICE_TYPE_SUPER_MAP);
            for (int i = 0; i < layerArray.size(); i++) {
                JSONObject layerJson = layerArray.getJSONObject(i);
                String url = layerJson.getString("url");
                String name = layerJson.getString("name");

                this.loadLayersBySuperMap(layerJson, mapLayerList);
            }
        }
        R r = saveParseLayers(mapLayerList, layerList, parentId, orgId, false);
        Object data = r.getData();
        if (data != null) {
            return R.data(data);
        } else {
            return r;
        }
    }

    /**
     * @描述: 保存解析的图层和服务
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:52
     **/
    private R saveParseLayers(List<MapLayer> mapLayerList, List<MapLayer> layerList, String parentId, String orgId, boolean updateFlag) {
        MapLayer parentLayer = mapLayerService.getById(parentId);
        Set<String> existsIds = new HashSet<>();
        if (!updateFlag) {
//            for(MapLayer mapLayer: mapLayerList) {
//                // 判断该图层同级下是否已存在
//                for (MapLayer temp : layerList) {
//                    if (Objects.equals(temp.getServerName(),mapLayer.getServerName())) {
//                        return R.fail( mapLayer.getName() + "该图层名已经存在！");
//                    }
//                }
//            }
        } else {
            existsIds = layerList.stream().map(MapLayer::getId).collect(Collectors.toSet());
        }
        Integer sort = commonService.getMaxSort(parentId, "map_layer");
        Long userId = getUser().getUserId();
        for (MapLayer mapLayer : mapLayerList) {
            sort++;
            mapLayer.setOrgId(orgId);
            mapLayer.setSort(sort);
            if (StringUtils.isBlank(mapLayer.getParentId())) {
                mapLayer.setParentId(parentId);
            }
            mapLayer.setParentName(parentLayer.getName());
            mapLayer.setCreateTime(new Date());
            mapLayer.setCreator(userId + "");
            if (existsIds.contains(mapLayer.getId())) {
                mapLayer.setCreator(null);
                mapLayer.setCreateTime(null);
                mapLayer.setModifier(userId + "");
                mapLayer.setModifyTime(new Date());
                mapLayerService.saveMaplayer(mapLayer, false);
            } else {
                mapLayerService.saveMaplayer(mapLayer, true);
            }
        }
        List<MapLayer> result = new ArrayList<>();
        for (MapLayer mapLayer : mapLayerList) {
            if (mapLayer.getName().indexOf(MapConst.TILE_INFO_STR) < 0) {
                result.add(mapLayer);
            }
        }
        return R.data(result);
    }

    /**
     * @描述:根据基础空间信息平台代理的Arcgis服务URL获取图层
     * @入参:
     * @出参:
     * @作者: 陈宏成
     * @日期: 2021-04-07
     **/
    private void loadLayersByBasisPlatform(String serverUrl, String layerTable, List<MapLayer> mapLayerList) {
        isServerFolder = layerTable == null ? true : false;
        Map<String, String> paramsMap = new HashMap<>();
        // originalUrl 原始url，没有追加参数那种
        String originalUrl = HttpRequester.getParamFromUrl(serverUrl, paramsMap);
        paramsMap.put("f", "pjson");
        // 读取数据源url获取json数据集
        String jsonStr = ReadFileUtil.getStringByUrl(originalUrl, paramsMap);
        if (StringUtils.isBlank(jsonStr)) {
            return;
        }
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        // 读取folders
        if (dataJson.get("folders") != null && StringUtils.isNotBlank(dataJson.getString("folders"))) {
            JSONArray folders = dataJson.getJSONArray("folders");
            for (int i = 0; i < folders.size(); i++) {
                String folderServerUrl = originalUrl + "/" + folders.getString(i);
                // 递归查询图层
                loadLayersByArcgis(HttpRequester.setParamToUrl(folderServerUrl, paramsMap), layerTable, mapLayerList, false, false);
            }
        }

        // 读取services
        if (dataJson.get("services") != null && StringUtils.isNotBlank(dataJson.getString("services"))) {
            JSONArray services = dataJson.getJSONArray("services");
            for (int i = 0; i < services.size(); i++) {
                JSONObject serviceJson = services.getJSONObject(i);
                String serviceType = serviceJson.getString("type");// 服务类型
                String serviceName = serviceJson.getString("name");// 服务名称
                if (StringUtils.isNotBlank(serviceType) && (serviceType.equalsIgnoreCase("MapServer") || serviceType.equalsIgnoreCase("FeatureServer"))) {
                    // 截取掉"/"前面的目录
                    serviceName = serviceName.lastIndexOf("/") == -1 ? serviceName : serviceName.substring(serviceName.lastIndexOf("/") + 1);
                    String serviceUrl = originalUrl + "/" + serviceName + "/" + serviceType;
                    // 递归查询图层
                    loadLayersByArcgis(HttpRequester.setParamToUrl(serviceUrl, paramsMap), layerTable, mapLayerList, false, false);
                }

            }
        }

        // 读取layers
        if (dataJson.get("layers") != null && StringUtils.isNotBlank(dataJson.getString("layers"))) {
            JSONArray layers = dataJson.getJSONArray("layers");
            for (int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                // 获取图层tableId
                String tableId = layerJson.getString("id");
                // 如果layerTable不为空，则只是拖动某个图层
                if (layerTable != null && !tableId.equals(layerTable) && !"-1".equals(layerTable)) {
                    continue;
                }

                // 根据图层url查询图层json数据集
                String serviceUrl = originalUrl + "/" + layerJson.getString("id");

                String layerJsonStr = ReadFileUtil.getStringByUrl(serviceUrl, paramsMap);
                JSONObject layerInfoJson = JSONObject.parseObject(layerJsonStr);
                // 获取图层几何类型
                String geometryType = layerInfoJson.get("geometryType") == null ? "" : layerInfoJson.getString("geometryType");
                // 图层类型、要素类型(默认切片)
                String layerType = "tclx_grid", featureType = "yslx_grid_2";
                if (geometryType.equalsIgnoreCase("esriGeometryPoint")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_point";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolyline")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polyline";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolygon")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polygon";
                }

                //根据当前url获取四至坐标
                R ajaxResult = this.loadLayerTable(serverUrl, MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                JSONObject serverJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
                String initialExtent = serverJson.getString("initialExtent");
                String spatialReference = serverJson.getString("wkid");
                // 加载方式(瓦片加载、动态加载)
                String loadType = (dataJson.get("tileInfo") != null && StringUtils.isNotBlank(dataJson.getString("tileInfo"))) ? "jzfs_tiled" : "jzfs_dynamic";

                MapLayer mapLayer = new MapLayer();
                mapLayer.setId(UuidUtil.get32UUID());
                mapLayer.setLayerType(layerType);
                mapLayer.setFeatureType(featureType);
                mapLayer.setLoadType(loadType);
                serverUrl = HttpRequester.getParamFromUrl(serverUrl, null);
                mapLayer.setLayerUrl(serverUrl);
                mapLayer.setServerUrl(serverUrl);
                mapLayer.setInitialExtent(initialExtent);
                mapLayer.setSpatialReference(spatialReference);
                mapLayer.setCreateTime(new Date());
                mapLayer.setUpdateTime(DateUtil.formatDate(new Date(), "yyyy-MM"));

                // 创建认证信息
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("key", MapConst.MAP_BASIS_PLATFORM_AUTH_TOKEN);
                jsonObject.put("value", paramsMap.get(MapConst.MAP_BASIS_PLATFORM_AUTH_TOKEN));
                mapLayer.setAuthKey(jsonObject.toJSONString());
                String[] serverArray = serverUrl.split("/");
                mapLayer.setServerName(serverArray[serverArray.length - 2]);
                if ("-1".equals(layerTable) && featureType.equals("yslx_grid_2")) {
                    mapLayer.setName(serverArray[serverArray.length - 2] + "(切片)");
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                    mapLayerList.add(mapLayer);
                    break;
                } else {
                    mapLayer.setName(layerJson.getString("name"));
                    mapLayer.setLayerTable(layerJson.getString("id"));
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                    mapLayerList.add(mapLayer);
                }
            }
        }
    }


    /**
     * @描述:
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/3/6 14:31
     **/
    private void loadLayersBySuperMap(JSONObject layerJson, List<MapLayer> mapLayerList) {
        if (layerJson != null) {
            String url = layerJson.getString("url");
            try {
                url = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

//            String name = layerJson.getString("name");
//            String layerType = layerJson.getString("layerType");
//            String initialExtent = layerJson.getString("initialExtent");
//            String baseMapType = layerJson.getString("baseMapType");
//            String alias = layerJson.getString("alias");
//            String spatialReference = layerJson.getString("spatialReference");
//            String layerTable = layerJson.getString("layerTable");
//
//            MapLayer mapLayer = new MapLayer();
//            mapLayer.setLayerUrl(url);
//            mapLayer.setName(name);
//            mapLayer.setLayerName(name);
//            mapLayer.setLayerType(layerType);
//            mapLayer.setInitialExtent(initialExtent);
//            mapLayer.setBaseMapType(baseMapType);
//            mapLayer.setAlias(StringUtils.isEmpty(alias) ? name : alias);
//            mapLayer.setReleaseType("iserver");
//            mapLayer.setSpatialReference(spatialReference);
//            mapLayer.setType("2");
//            mapLayer.setLayerTable(layerTable);

            MapLayer mapLayer = JSONObject.parseObject(String.valueOf(layerJson), MapLayer.class);
            mapLayer.setAlias(StringUtils.isEmpty(mapLayer.getAlias()) ? mapLayer.getName() : mapLayer.getAlias());
            mapLayer.setReleaseType("iserver");
            mapLayer.setType("2");
            mapLayer.setLayerName(mapLayer.getName());
            mapLayer.setLayerUrl(url);
            mapLayerList.add(mapLayer);
        }
    }

    /**
     * @描述: 根据Arcgis服务URL获取图层
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:54
     **/
    private void loadLayersByArcgis(final String serverUrl, final String layerTable, List<MapLayer> mapLayerList, boolean flag, boolean allFlag) {
        isServerFolder = layerTable == null ? true : false;
        // 判断数据图层URL是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(serverUrl);
        if (!isExists) {
            return;
        }

        // 读取数据源url获取json数据集
        String jsonStr = ReadFileUtil.getStringByUrl(serverUrl + "?f=pjson");
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        // 读取folders
        if (dataJson.get("folders") != null && StringUtils.isNotBlank(dataJson.getString("folders"))) {
            JSONArray folders = dataJson.getJSONArray("folders");
            for (int i = 0; i < folders.size(); i++) {
                String folderServerUrl = serverUrl + "/" + folders.getString(i);
                // 递归查询图层
                loadLayersByArcgis(folderServerUrl, layerTable, mapLayerList, flag, allFlag);
            }
        }

        // 读取services
        if (dataJson.get("services") != null && StringUtils.isNotBlank(dataJson.getString("services"))) {
            JSONArray services = dataJson.getJSONArray("services");
            for (int i = 0; i < services.size(); i++) {
                JSONObject serviceJson = services.getJSONObject(i);
                String serviceType = serviceJson.getString("type");// 服务类型
                String serviceName = serviceJson.getString("name");// 服务名称
                if (StringUtils.isNotBlank(serviceType) && (serviceType.equalsIgnoreCase("MapServer") || serviceType.equalsIgnoreCase("FeatureServer"))) {
                    // 截取掉"/"前面的目录
                    serviceName = serviceName.lastIndexOf("/") == -1 ? serviceName : serviceName.substring(serviceName.lastIndexOf("/") + 1);
                    String serviceUrl = serverUrl + "/" + serviceName + "/" + serviceType;
                    // 递归查询图层
                    loadLayersByArcgis(serviceUrl, layerTable, mapLayerList, flag, allFlag);
                }

            }
        }
        // 标记是否是瓦片服务
        boolean tileInfo = false;
        String layerType = mapLayerService.getLayerType(serverUrl, dataJson);
        if (dataJson.containsKey("tileInfo")) {
            tileInfo = true;
        }
        boolean showLayerFlag = dataSourceService.showLayerFlag(serverUrl, tileInfo);
        // 读取layers
        if (dataJson.get("layers") != null && StringUtils.isNotBlank(dataJson.getString("layers"))) {
            JSONArray layers = dataJson.getJSONArray("layers");
            for (int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                if (StringUtils.isBlank(layerType)) {
                    layerType = mapLayerService.getLayerType(serverUrl, layerJson);
                }
//                if(tileInfo) {
//                    MapLayer mapLayer = mapLayerList.get(0);
//                    String substring = serverUrl.substring(0, serverUrl.indexOf("/MapServer"));
//                    String name = substring.substring(substring.lastIndexOf("/") + 1);
//                    mapLayer.setName(name);
//                    mapLayer.setLayerType("tclx_tile");
//                    break;
//                }

                // 获取图层tableId
                String tableId = layerJson.getString("id");
                // 如果layerTable不为空，则只是拖动某个图层
                if (!tileInfo && layerTable != null && !tableId.equals(layerTable) && !"-1".equals(layerTable) && showLayerFlag && !allFlag) {
                    continue;
                }
                if (dataJson.containsKey("tileInfo")) {
                    tileInfo = true;
                }
                // 根据图层url查询图层json数据集
                String serviceUrl = serverUrl + "/" + layerJson.getString("id") + "?f=pjson";
                String layerJsonStr = ReadFileUtil.getStringByUrl(serviceUrl);
                JSONObject layerInfoJson = JSONObject.parseObject(layerJsonStr);
                // 获取图层几何类型
                String geometryType = layerInfoJson.get("geometryType") == null ? "" : layerInfoJson.getString("geometryType");
                // 图层类型、要素类型(默认切片)
                String featureType = getFeatureType(geometryType);

                //根据当前url获取四至坐标
                R ajaxResult = this.loadLayerTable(serverUrl, MapConst.MAP_SERVICE_TYPE_ARCGIS);
                JSONObject serverJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
                String initialExtent = serverJson.getString("initialExtent");
                String spatialReference = serverJson.getString("wkid");
                if (StringUtils.isBlank(spatialReference)) {
                    Object spatialReferenceObj = layerJson.get("spatialReference");
                    if (spatialReferenceObj != null) {
                        JSONObject spatialReferenceJson = (JSONObject) spatialReferenceObj;
                        Object wkid = spatialReferenceJson.get("wkid");
                        if (wkid != null) {
                            spatialReference = wkid.toString();
                        }
                    }
                }
                // 加载方式(瓦片加载、动态加载)
                String loadType = (dataJson.get("tileInfo") != null && StringUtils.isNotBlank(dataJson.getString("tileInfo"))) ? "jzfs_tiled" : "jzfs_dynamic";
                /*if(isServerFolder && loadType.equals("jzfs_tiled")){
                    isServerFolder = false;
                    // 新增切片图层
                    MapLayer mapLayer = new MapLayer();
                    mapLayer.setId(this.get32UUID());
                    mapLayer.setLayerType(layerType);
                    mapLayer.setFeatureType(featureType);
                    mapLayer.setLoadType(loadType);
                    mapLayer.setLayerUrl(serverUrl);
                    mapLayer.setServerUrl(serverUrl);
                    String[] serverArray = serverUrl.split("/");
                    mapLayer.setName(serverArray[serverArray.length-2]+"(切片)");
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                    mapLayerList.add(mapLayer);
                }*/
                MapLayer mapLayer = new MapLayer();
                mapLayer.setId(UuidUtil.get32UUID());
                mapLayer.setLayerType(layerType);
                mapLayer.setFeatureType(featureType);
                mapLayer.setLoadType(loadType);
                mapLayer.setLayerUrl(serverUrl);
                mapLayer.setServerUrl(serverUrl);
                mapLayer.setInitialExtent(initialExtent);
                mapLayer.setSpatialReference(spatialReference);
                mapLayer.setType("3");
                String[] serverArray = serverUrl.split("/");
                mapLayer.setServerName(serverArray[serverArray.length - 2]);
//                int mapServerIdx = serverUrl.indexOf(mapServerStr);
//                boolean mapTileFlag=false;
//                //地图切片服务
//                if(mapServerIdx>0&&tileInfo){
//                    mapTileFlag=true;
//                }
                if ("-1".equals(layerTable) && featureType.equals("yslx_grid_2")) {
                    mapLayer.setName(serverArray[serverArray.length - 2] + "(切片)");
                    if (!showLayerFlag) {
                        mapLayer.setName(layerJson.getString("name") + MapConst.TILE_INFO_STR);
                    }
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                } else {
                    mapLayer.setName(layerJson.getString("name"));
                    if (!showLayerFlag) {
                        mapLayer.setName(layerJson.getString("name") + MapConst.TILE_INFO_STR);
                    }
                    mapLayer.setLayerTable(layerJson.getString("id"));
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                }
                mapLayer.setAlias(layerJson.getString("name"));
                mapLayerList.add(mapLayer);
            }
        }
        // 解析没有图层或隐藏图层的服务
        fillService(mapLayerList, layerType, dataJson, serverUrl, layerTable, flag, showLayerFlag);
        setHideLayersParent(mapLayerList, allFlag);
    }

    /**
     * @描述: 设置隐藏图层的parentId
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:55
     **/
    private void setHideLayersParent(List<MapLayer> mapLayerList, boolean allFlag) {
        if (mapLayerList == null || mapLayerList.isEmpty()) {
            return;
        }
        Map<String, String> serverUrlAndParenId = new HashMap<>();
        Map<String, List<String>> childLayerTable = new HashMap<>();
        for (MapLayer mapLayer : mapLayerList) {
            String serverUrl = mapLayer.getServerUrl();
            if ("2".equals(mapLayer.getType())) {
                serverUrlAndParenId.put(serverUrl, mapLayer.getId());
            } else if ("3".equals(mapLayer.getType())) {
                List<String> layerTable = childLayerTable.get(serverUrl);
                if (layerTable == null) {
                    layerTable = new ArrayList<>();
                }
                layerTable.add(mapLayer.getLayerTable());
                childLayerTable.put(serverUrl, layerTable);
            }
        }
        for (MapLayer mapLayer : mapLayerList) {
            String serverUrl = mapLayer.getServerUrl();
            if ("3".equals(mapLayer.getType())) {
                String parentId = serverUrlAndParenId.get(serverUrl);
                if (StringUtils.isNotBlank(parentId)) {
                    mapLayer.setParentId(parentId);
                }
            } else if ("2".equals(mapLayer.getType())) {
                List<String> layerTables = childLayerTable.get(serverUrl);
                if (layerTables != null && !layerTables.isEmpty() && allFlag) {
                    mapLayer.setLayerTable(String.join(",", layerTables));
                }
            }
        }
    }

    /**
     * @描述: 解析没有图层或隐藏图层的服务
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:55
     **/
    private void fillService(List<MapLayer> mapLayerList, String layerType, JSONObject serverResult, String serverUrl, String layerTable, boolean flag, boolean showLayerFlag) {
        if (!flag) {
            return;
        }
        List<String> serverStrList = new ArrayList<>();
        serverStrList.add(MapConst.MAP_SERVER_STR);
        serverStrList.add(MapConst.IMAGE_SERVER_STR);
        serverStrList.add(MapConst.FEATURE_SERVER_STR);
        serverStrList.add(MapConst.VECTOR_TILE_SERVER_STR);
        serverStrList.add(MapConst.SCENE_LAYER_STR);
        StringBuilder serverStr = new StringBuilder("^.*(");
        for (String str : serverStrList) {
            serverStr.append(str + "|");
        }
        serverStr.deleteCharAt(serverStr.length() - 1);
        serverStr.append(").*$");
        Pattern pattern = Pattern.compile(serverStr.toString());
        boolean matches = pattern.matcher(serverStr).matches();
        if (!matches) {
            return;
        }
        Object layers = serverResult.get("layers");
        if (layers != null && showLayerFlag) {
            return;
        }
        Object geometryTypeObj = serverResult.get("geometryType");
        String geometryType = "";
        if (geometryTypeObj != null) {
            geometryType = geometryTypeObj.toString();
        }
        String featureType = getFeatureType(geometryType);
        Object initialExtent = serverResult.get("initialExtent");
        // spatialReference
        Object spatialReferenceObj = serverResult.get("spatialReference");
        String spatialReference = "";
        if (spatialReferenceObj != null) {
            JSONObject spatialReferenceJson = (JSONObject) spatialReferenceObj;
            Object wkid = spatialReferenceJson.get("wkid");
            if (wkid != null) {
                spatialReference = wkid.toString();
            } else {
                spatialReference = spatialReferenceJson.get("wkt") == null ? "" : spatialReferenceJson.get("wkt").toString();
            }
        } else {
            Object serviceLayer = serverResult.get("layers");
            if (serviceLayer != null && !"null".equalsIgnoreCase(serviceLayer.toString()) && StringUtils.isNotBlank(serviceLayer.toString())) {
                JSONArray layerArray = (JSONArray) serviceLayer;
                if (!layerArray.isEmpty()) {
                    JSONObject oneLayer = (JSONObject) layerArray.get(0);
                    Object spatialReferenceStr = oneLayer.get("spatialReference");
                    if (spatialReferenceStr != null) {
                        JSONObject spatialReferenceJson = (JSONObject) spatialReferenceStr;
                        Object wkid = spatialReferenceJson.get("wkid");
                        if (wkid != null) {
                            spatialReference = wkid.toString();
                        } else {
                            spatialReference = oneLayer.get("wkt") == null ? "" : oneLayer.get("wkt").toString();
                        }
                    }
                }
            }
        }
        String loadType = (serverResult.get("tileInfo") != null && StringUtils.isNotBlank(serverResult.getString("tileInfo"))) ? "jzfs_tiled" : "jzfs_dynamic";
        MapLayer mapLayer = new MapLayer();
        mapLayer.setId(UuidUtil.get32UUID());
        mapLayer.setLayerType(layerType);
        mapLayer.setFeatureType(featureType);
        mapLayer.setLoadType(loadType);
        mapLayer.setLayerUrl(serverUrl);
        mapLayer.setServerUrl(serverUrl);
        mapLayer.setInitialExtent(initialExtent == null ? "" : initialExtent.toString());
        mapLayer.setSpatialReference(spatialReference);
        mapLayer.setType("2");
        String[] serverArray = serverUrl.split("/");
        mapLayer.setAlias(serverArray[serverArray.length - 2]);
        mapLayer.setServerName(serverArray[serverArray.length - 2]);
        mapLayer.setName(serverArray[serverArray.length - 2]);
        mapLayer.setLayerTable("-1");
        mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
        mapLayerList.add(mapLayer);
    }

    private String getFeatureType(String geometryType) {
        String featureType = "yslx_grid_2";
        if (geometryType.equalsIgnoreCase("esriGeometryPoint")) {
            featureType = "yslx_point";
        } else if (geometryType.equalsIgnoreCase("esriGeometryPolyline")) {
            featureType = "yslx_polyline";
        } else if (geometryType.equalsIgnoreCase("esriGeometryPolygon")) {
            featureType = "yslx_polygon";
        }
        return featureType;
    }

    /**
     * @描述：根据基础信息平台服务地址获取图层集合(吉奥)
     * @作者：彭辉
     * @日期：2020/12/2 16:00
     **/
    public void loadLayersByPlatform(String serverUrl, String layerTable, Map<String, String> paramMap, List<MapLayer> mapLayerList) {
        // 判断数据图层URL是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(serverUrl);
        if (!isExists) {
            return;
        }
        paramMap.put("f", "pjson");
        // 读取数据源url获取json数据集
        String jsonStr = ReadFileUtil.getStringByUrl(serverUrl, paramMap);
        JSONObject dataJson = JSONObject.parseObject(jsonStr);

        // 读取layers
        if (dataJson.get("layers") != null && StringUtils.isNotBlank(dataJson.getString("layers"))) {
            JSONArray layers = dataJson.getJSONArray("layers");
            for (int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                // 获取图层tableId
                String tableId = layerJson.getString("id");
                // 如果layerTable不为空，则只是拖动某个图层
                if (layerTable != null && !tableId.equals(layerTable) && !"-1".equals(layerTable)) {
                    continue;
                }
                // 根据图层url查询图层json数据集
                String layerJsonStr = ReadFileUtil.getStringByUrl(serverUrl + "/" + layerJson.getString("id"), paramMap);
                JSONObject layerInfoJson = JSONObject.parseObject(layerJsonStr);
                // 获取图层几何类型
                String geometryType = layerInfoJson.get("geometryType") == null ? "" : layerInfoJson.getString("geometryType");
                // 图层类型、要素类型(默认切片)
                String layerType = "tclx_grid", featureType = "yslx_grid_2";
                if (geometryType.equalsIgnoreCase("esriGeometryPoint")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_point";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolyline")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polyline";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolygon")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polygon";
                }

                //根据当前url获取四至坐标
                R ajaxResult = this.loadLayerTable(serverUrl + "?" + MapConst.MAP_PLATFORM_AUTH_TOKEN + "=" + paramMap.get(MapConst.MAP_PLATFORM_AUTH_TOKEN), MapConst.MAP_SERVICE_TYPE_PLATFORM);
                JSONObject serverJson = (JSONObject) JSON.toJSON(ajaxResult.getData());
                String initialExtent = serverJson.getString("initialExtent");
                String spatialReference = serverJson.getString("wkid");
                // 加载方式(瓦片加载、动态加载)
                String loadType = (dataJson.get("tileInfo") != null && StringUtils.isNotBlank(dataJson.getString("tileInfo"))) ? "jzfs_tiled" : "jzfs_dynamic";
                /* if(loadType.equals("jzfs_tiled")){
                    // 新增切片图层
                    MapLayer mapLayer = new MapLayer();
                    mapLayer.setId(this.get32UUID());
                    mapLayer.setLayerType(layerType);
                    mapLayer.setFeatureType(featureType);
                    mapLayer.setLoadType(loadType);
                    mapLayer.setLayerUrl(serverUrl);
                    mapLayer.setServerUrl(serverUrl);
                    String[] serverArray = serverUrl.split("/");
                    mapLayer.setName(serverArray[serverArray.length-2]+"(切片)");
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_PLATFORM);
                    mapLayer.setInitialExtent(initialExtent);
                    mapLayer.setSpatialReference(spatialReference);
                    mapLayer.setAuthKey("{\"key\":\"" + MapConst.MAP_PLATFORM_AUTH_TOKEN + "\", \"value\":\"" + paramMap.get(MapConst.MAP_PLATFORM_AUTH_TOKEN) + "\"}");
                    mapLayerList.add(mapLayer);
                }*/

                MapLayer mapLayer = new MapLayer();
                mapLayer.setId(UuidUtil.get32UUID());
                mapLayer.setLayerType(layerType);
                mapLayer.setFeatureType(featureType);
                mapLayer.setLoadType(loadType);
                mapLayer.setLayerUrl(serverUrl);
                mapLayer.setServerUrl(serverUrl);
                mapLayer.setInitialExtent(initialExtent);
                mapLayer.setSpatialReference(spatialReference);
                mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_PLATFORM);
                mapLayer.setAuthKey("{\"key\":\"" + MapConst.MAP_PLATFORM_AUTH_TOKEN + "\", \"value\":\"" + paramMap.get(MapConst.MAP_PLATFORM_AUTH_TOKEN) + "\"}");

                String[] serverArray = serverUrl.split("/");
                mapLayer.setServerName(serverArray[serverArray.length - 2]);
                // if(loadType.equals("jzfs_tiled")){
                if (featureType.equals("yslx_grid_2")) {
                    mapLayer.setName(serverArray[serverArray.length - 2]);
                    mapLayer.setLayerTable(layerJson.getString("id"));
                    mapLayerList.add(mapLayer);
                    break;
                } else {
                    mapLayer.setName(layerJson.getString("name"));
                    mapLayer.setLayerTable(layerJson.getString("id"));
                    mapLayerList.add(mapLayer);
                }
            }
        }
    }

    /**
     * @描述:根据吉奥基础信息平台服务URL获取图层
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/27 17:20
     **/
    private void loadLayersByArcgisPlatform(String serverUrl, String layerTable, Map<String, String> params, List<MapLayer> mapLayerList) {
        isServerFolder = layerTable == null ? true : false;
        // 判断数据图层URL是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(serverUrl);
        if (!isExists) {
            return;
        }

        String jsonStr = ReadFileUtil.getStringByUrl(serverUrl, params);
        JSONObject dataJson = JSONObject.parseObject(jsonStr);
        // 读取folders
        if (dataJson.get("folders") != null && StringUtils.isNotBlank(dataJson.getString("folders"))) {
            JSONArray folders = dataJson.getJSONArray("folders");
            for (int i = 0; i < folders.size(); i++) {
                String folderServerUrl = serverUrl + "/" + folders.getString(i);
                // 递归查询图层
                loadLayersByArcgisPlatform(folderServerUrl, layerTable, params, mapLayerList);
            }
        }

        // 读取services
        if (dataJson.get("services") != null && StringUtils.isNotBlank(dataJson.getString("services"))) {
            JSONArray services = dataJson.getJSONArray("services");
            for (int i = 0; i < services.size(); i++) {
                JSONObject serviceJson = services.getJSONObject(i);
                String serviceType = serviceJson.getString("type");// 服务类型
                String serviceName = serviceJson.getString("name");// 服务名称
                if (StringUtils.isNotBlank(serviceType) && (serviceType.equalsIgnoreCase("MapServer") || serviceType.equalsIgnoreCase("FeatureServer"))) {
                    // 截取掉"/"前面的目录
                    serviceName = serviceName.lastIndexOf("/") == -1 ? serviceName : serviceName.substring(serviceName.lastIndexOf("/") + 1);
                    String serviceUrl = serverUrl + "/" + serviceName + "/" + serviceType;
                    // 递归查询图层
                    loadLayersByArcgisPlatform(serviceUrl, layerTable, params, mapLayerList);
                }

            }
        }

        // 读取layers
        if (dataJson.get("layers") != null && StringUtils.isNotBlank(dataJson.getString("layers"))) {
            JSONArray layers = dataJson.getJSONArray("layers");
            for (int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                // 获取图层tableId
                String tableId = layerJson.getString("id");
                // 如果layerTable不为空，则只是拖动某个图层
                if (layerTable != null && !tableId.equals(layerTable) && !"-1".equals(layerTable)) {
                    continue;
                }

                // 根据图层url查询图层json数据集
                String serviceUrl = serverUrl + "/" + layerJson.getString("id");
                String layerJsonStr = ReadFileUtil.getStringByUrl(serviceUrl, params);
                JSONObject layerInfoJson = JSONObject.parseObject(layerJsonStr);
                // 获取图层几何类型
                String geometryType = layerInfoJson.get("geometryType") == null ? "" : layerInfoJson.getString("geometryType");
                // 图层类型、要素类型(默认切片)
                String layerType = "tclx_grid", featureType = "yslx_grid_2";
                if (geometryType.equalsIgnoreCase("esriGeometryPoint")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_point";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolyline")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polyline";
                } else if (geometryType.equalsIgnoreCase("esriGeometryPolygon")) {
                    layerType = "tclx_rest";
                    featureType = "yslx_polygon";
                }
                // 加载方式(瓦片加载、动态加载)
                String loadType = (dataJson.get("tileInfo") != null && StringUtils.isNotBlank(dataJson.getString("tileInfo"))) ? "jzfs_tiled" : "jzfs_dynamic";
                /* if(isServerFolder && loadType.equals("jzfs_tiled")){
                    isServerFolder = false;
                    // 新增切片图层
                    MapLayer mapLayer = new MapLayer();
                    mapLayer.setId(this.get32UUID());
                    mapLayer.setLayerType(layerType);
                    mapLayer.setFeatureType(featureType);
                    mapLayer.setLoadType(loadType);
                    mapLayer.setLayerUrl(serverUrl);
                    mapLayer.setServerUrl(serverUrl);
                    String[] serverArray = serverUrl.split("/");
                    mapLayer.setName(serverArray[serverArray.length-2]+"(切片)");
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                    mapLayer.setAuthKey("{\"key\":\"gtkjgh_tk\",\"value\":\""+params.get("gtkjgh_tk")+"\"}");
                    mapLayerList.add(mapLayer);
                }*/

                MapLayer mapLayer = new MapLayer();
                mapLayer.setId(UuidUtil.get32UUID());
                mapLayer.setLayerType(layerType);
                mapLayer.setFeatureType(featureType);
                mapLayer.setLoadType(loadType);
                mapLayer.setLayerUrl(serverUrl);
                mapLayer.setServerUrl(serverUrl);
                mapLayer.setAuthKey("{\"key\":\"" + MapConst.MAP_PLATFORM_AUTH_TOKEN + "\",\"value\":\"" + params.get(MapConst.MAP_PLATFORM_AUTH_TOKEN) + "\"}");
                if ("-1".equals(layerTable) && loadType.equals("jzfs_tiled")) {
                    String[] serverArray = serverUrl.split("/");
                    mapLayer.setName(serverArray[serverArray.length - 2] + "(切片)");
                    mapLayer.setLayerTable("-1");
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                    mapLayerList.add(mapLayer);
                    break;
                } else {
                    mapLayer.setName(layerJson.getString("name"));
                    mapLayer.setLayerTable(layerJson.getString("id"));
                    mapLayer.setReleaseType(MapConst.MAP_SERVICE_TYPE_ARCGIS);
                    mapLayerList.add(mapLayer);
                }
            }
        }
    }

    /**
     * @描述: 根据iserver服务URL获取图层
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/4/26 16:54
     **/
    private void loadLayersByIserver(String serverUrl, List<MapLayer> mapLayerList) {
        //图层名称
        String name = "";
        //解析wms服务
        if (serverUrl.indexOf("wmts") != -1 || serverUrl.indexOf("wms") != -1) {
            String keyWord = "";
            try {
                keyWord = URLDecoder.decode(serverUrl, "UTF-8");
            } catch (Exception e) {
            }
            name = serverUrl.substring(keyWord.lastIndexOf("/") + 1, keyWord.length());
        } else {
            String jsonStr = ReadFileUtil.getJsonByUrl(serverUrl + ".json");
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            name = jsonObject.getString("name");
        }
        MapLayer mapLayer = new MapLayer();
        mapLayer.setId(UuidUtil.get32UUID());
        mapLayer.setLayerUrl(serverUrl);
        mapLayer.setServerUrl(serverUrl);
        mapLayer.setName(name);
        if (serverUrl.indexOf("rest") != -1) {
            mapLayer.setLayerType("tclx_rest");
        } else if (serverUrl.indexOf("wms") != -1) {
            mapLayer.setLayerType("tclx_wms");
        } else if (serverUrl.indexOf("wmts") != -1) {
            mapLayer.setLayerType("tclx_wmts");
        } else {
            mapLayer.setLayerType("tclx_rest");
        }
        mapLayer.setReleaseType("iserver");
        mapLayer.setLayerTable("0");
        //设置默认加载方式
        if (mapLayer.getLayerUrl().indexOf("vectortile") != -1) {
            mapLayer.setLoadType("jzfs_vectortile");
        } else {
            mapLayer.setLoadType("jzfs_tiled");
        }
        mapLayerList.add(mapLayer);
    }

    /**
     * @描述: 获取所有类型为底图的数据
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/1/7 10:41
     **/
    @PostMapping("/getBaseMap")
    @ApiOperation(value = "获取所有类型为底图的数据")
    public R getBaseMap() {
        //查询用户组织--新基础运维
        List<MapLayer> list = mapLayerService.getBaseMap();
        return R.data(list);
    }

    /**
     * @描述: 地图服务拖拽排序
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/2/20 10:42
     **/
    @PostMapping("/moveSort")
    @ApiOperation(value = "地图服务拖拽排序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "当前拖拽ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "targetId", value = "目标位置ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ahead", value = "是否拖拽到目标位置下方(true:是 false:否)", required = true, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "拖拽到的机构ID", required = true, dataType = "string", paramType = "query")
    })
    public R moveSort(String id, String targetId, Boolean ahead, String orgId) {
        //获取目标数据
        MapLayer targetData = mapLayerService.getById(targetId);
        //获取所有跟目标同级的数据
        MapLayer moveData = mapLayerService.getById(id);
        String oldParentId = moveData.getParentId();
        Integer sort = moveData.getSort();
        List<MapLayer> mapLayers = (List<MapLayer>) mapLayerService.listByMap(VerificationUtil.verifyMap("", moveData.getParentId()));
        if (ahead) {
            //拖拽至目标下方的情况
            updateSort(moveData, targetData, orgId, true);
        } else {
            //拖拽至目标上方的情况
            updateSort(moveData, targetData, orgId, false);
        }
        //移动完成后，需要修改被移动数据同级的数据序号
        List<MapLayer> saveData = mapLayers.stream().filter(s -> !s.getId().equals(id)).collect(Collectors.toList());
        if (saveData.size() > 0) {
            if (!saveData.get(0).getParentId().equals(oldParentId)) {
                for (MapLayer mapLayer : saveData) {
                    if (mapLayer.getSort() > sort) {
                        mapLayer.setSort(mapLayer.getSort() - 1);
                    }
                }
                mapLayerService.updateBatchById(saveData);
            }
        }
        return R.data(null);
    }

    private void updateSort(MapLayer mf, MapLayer mapLayer, String orgId, Boolean isAhead) {
        //1.查询当前拖拽到的目标父目录下所有的数据
        List<MapLayer> mapLayerList = (List<MapLayer>) mapLayerService.listByMap(VerificationUtil.verifyMap("", mapLayer.getParentId()));
        if (!isAhead) {
            //2.拖拽至目标上方
            //同级拖拽
            if (mf.getParentId().equals(mapLayer.getParentId())) {
                if (mf.getSort() > mapLayer.getSort()) {
                    for (MapLayer mapLayer1 : mapLayerList) {
                        if (mapLayer1.getSort() < mf.getSort() && mapLayer1.getSort() >= mapLayer.getSort()) {
                            mapLayer1.setSort(mapLayer1.getSort() + 1);
                        }
                    }
                    //3.更新排序
                    mf.setSort(mapLayer.getSort());
                } else {
                    for (MapLayer mapLayer1 : mapLayerList) {
                        if (mapLayer1.getSort() > mf.getSort() && mapLayer1.getSort() < mapLayer.getSort()) {
                            mapLayer1.setSort(mapLayer1.getSort() - 1);
                        }
                    }
                    //3.更新排序
                    mf.setSort(mapLayer.getSort() - 1);
                }
            } else {
                for (MapLayer mapLayer1 : mapLayerList) {
                    if (mapLayer1.getSort() >= mapLayer.getSort()) {
                        mapLayer1.setSort(mapLayer1.getSort() + 1);
                    }
                }
                //3.更新排序
                mf.setSort(mapLayer.getSort());
            }
            mapLayerService.updateBatchById(mapLayerList);
        } else {
            //2.拖拽至目标下方
            //同级排序
            if (mf.getParentId().equals(mapLayer.getParentId())) {
                if (mf.getSort() < mapLayer.getSort()) {
                    for (MapLayer mapLayer1 : mapLayerList) {
                        if (mapLayer1.getSort() > mf.getSort() && mapLayer1.getSort() <= mapLayer.getSort()) {
                            mapLayer1.setSort(mapLayer1.getSort() - 1);
                        }
                    }
                    //3.更新排序
                    mf.setSort(mapLayer.getSort());
                } else {
                    for (MapLayer mapLayer1 : mapLayerList) {
                        if (mapLayer1.getSort() < mf.getSort() && mapLayer1.getSort() > mapLayer.getSort()) {
                            mapLayer1.setSort(mapLayer1.getSort() + 1);
                        }
                    }
                    //3.更新排序
                    mf.setSort(mapLayer.getSort() + 1);
                }
            } else {
                //非同级排序
                for (MapLayer mapLayer1 : mapLayerList) {
                    if (mapLayer1.getSort() > mapLayer.getSort()) {
                        mapLayer1.setSort(mapLayer1.getSort() + 1);
                    }
                }
                //3.更新排序
                mf.setSort(mapLayer.getSort() + 1);
            }
            mapLayerService.updateBatchById(mapLayerList);
        }
        //4.更新拖拽的数据
        mf.setOrgId(orgId);
        mf.setParentId(mapLayer.getParentId());
        mapLayerService.updateById(mf);
    }

//    /**
//     * @描述: 获取图层相关下拉框的数据字典
//     * @入参:
//     * @出参:
//     * @作者: 代鹏刚
//     * @日期: 2020/3/25 15:50
//     **/
//    @PostMapping("/getDictionaryList")
//    @ApiOperation(value = "获取图层相关下拉框的数据字典")
//    public R getDictionaryList(){
//        Map<String,Object> map = new HashMap<>();
//        // 获取数据字典：图层类型 --新基础运维
//        List<Map<String, String>> layerTypeList = iRedisDictService.getItems("TCLX");
//        List<Map<String, String>> featureTypeList = iRedisDictService.getItems("YSLX");
//        List<Map<String, String>> loadTypeList = iRedisDictService.getItems("JZFS");
//        map.put("layerTypeList",layerTypeList);
//        map.put("featureTypeList",featureTypeList);
//        map.put("loadTypeList",loadTypeList);
//        return R.data(map);
//    }

    /**
     * @描述: 查询模型因子关联图层列表
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/6/17 17:46
     **/
    @PostMapping("/listMapLayerByFactor")
    @ApiOperation(value = "查询模型因子关联图层列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "layerId", value = "关联图层ID（多个图层ID逗号隔开）", required = true, dataType = "string", paramType = "query")
    })
    public R listMapLayerByFactor(String layerId) {
        if (StringUtils.isNotBlank(layerId)) {
            String[] layerIds = layerId.split(",");
            List<MapLayer> mapLayerList = (List<MapLayer>) mapLayerService.listByIds(Arrays.asList(layerIds));
            return R.data(mapLayerList);
        }
        return R.data(null);
    }

    private boolean prepareData(MapLayer mapLayer, boolean isSave) {
        //判断当前目录下，图层名称是否存在
        Map map = VerificationUtil.verifyMap(mapLayer.getName(), mapLayer.getParentId());
//        map.remove("name");
//        map.put("alias",mapLayer.getAlias());
        List<MapLayer> list = (List<MapLayer>) mapLayerService.listByMap(map);
        if (isSave) {
            if (list.size() > 0) {
                return false;
            }
            mapLayer.setCreator(getUser().getUserId().toString());
            mapLayer.setCreateTime(new Date());
            //防止误修改
            mapLayer.setModifier(null);
            mapLayer.setModifyTime(null);
            return true;
        } else {
            if (list.size() > 0 && !list.get(0).getId().equals(mapLayer.getId())) {
                return false;
            }
//            mapLayer.setModifier(getUser().getUserId().toString());
            mapLayer.setModifyTime(new Date());
            //防止误修改
            mapLayer.setCreator(null);
            mapLayer.setCreateTime(null);
            return true;
        }
    }

    /**
     * @描述: 服务地址修改的情况
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:56
     **/
    public boolean changeUrl(MapLayer mapLayer) {
        final String layerUrl = mapLayer.getLayerUrl();
        MapLayer originLayer = mapLayerService.getById(mapLayer.getId());
        if (StringUtils.isBlank(originLayer.getLayerUrl()) || originLayer.getLayerUrl().equals(layerUrl)) {
            return false;
        }
        String stringByUrl = ReadFileUtil.getStringByUrl(layerUrl + MapConst.URL_SUFFIX);
        if (!mapLayerService.ogcFlag(layerUrl)) {
            List<MapLayer> resultList = new ArrayList<>();
            boolean hideLayerFlag = saveHideLayerService(mapLayer, resultList, stringByUrl, true);
            if (hideLayerFlag) {
                for (MapLayer layer : resultList) {
                    if (mapLayer.getId().equals(layer.getId())) {
                        BeanUtils.copyProperties(layer, mapLayer);
                    }
                }
                return true;
            }
        }
        fillLayer(mapLayer, stringByUrl);
        mapLayerService.saveMaplayer(mapLayer, false);
        mapLayerService.syncLayerName(Arrays.asList(mapLayer));
        return true;
    }

    private void fillLayer(MapLayer mapLayer, String stringByUrl) {
        if (StringUtils.isNotBlank(mapLayer.getLayerTable())) {
            mapLayer.setType("3");
        } else {
            mapLayer.setType("2");
        }
        String[] serverArray = mapLayer.getLayerUrl().split("/");
        String serviceName = serverArray[serverArray.length - 2];
        if (StringUtils.isNotBlank(stringByUrl)) {
            JSONObject serviceResult = (JSONObject) JSONObject.parse(stringByUrl);
            Object layersObj = serviceResult.get("layers");
            if (layersObj == null) {
                mapLayer.setName(serviceName);
            }
        }
        mapLayer.setServerUrl(mapLayer.getLayerUrl());
        mapLayer.setServerName(serviceName);
    }

    /**
     * @描述: 保存隐藏图层的服务
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2022/4/28 18:56
     **/
    private boolean saveHideLayerService(MapLayer mapLayer, List<MapLayer> result, String stringByUrl, boolean updateFlag) {
        String layerUrl = mapLayer.getLayerUrl();
        boolean tileFlag = false;
        if (StringUtils.isNotBlank(stringByUrl)) {
            JSONObject serviceResult = (JSONObject) JSONObject.parse(stringByUrl);
            Object tileInfo = serviceResult.get("tileInfo");
            if (tileInfo != null) {
                tileFlag = true;
            }
        }
        if (dataSourceService.showLayerFlag(layerUrl, tileFlag)) {
            return false;
        }
        loadLayersByArcgis(layerUrl, mapLayer.getLayerTable(), result, true, false);
        if (!result.isEmpty()) {
            // 根据父目录id查询所有图层
            List<MapLayer> layerList = (List<MapLayer>) mapLayerService.listByMap(VerificationUtil.verifyMap(null, mapLayer.getParentId()));
            Map<String, String> setParentId = new HashMap<>();
            for (MapLayer layer : result) {
                if (updateFlag && "2".equals(layer.getType())) {
                    setParentId.put(layer.getId(), mapLayer.getId());
                    layer.setId(mapLayer.getId());
                }
                if ("2".equals(layer.getType())) {
                    layer.setLongitude(mapLayer.getLongitude());
                    layer.setLatitude(mapLayer.getLatitude());
                    layer.setHeight(mapLayer.getHeight());
                    layer.setAzimuthAngle(mapLayer.getAzimuthAngle());
                    layer.setDepressionAngle(mapLayer.getDepressionAngle());
                    layer.setDeviation(mapLayer.getDeviation());
                    layer.setUnit(mapLayer.getUnit());
                    layer.setElevationPattern(mapLayer.getElevationPattern());
                    layer.setLazyLoad(mapLayer.getLazyLoad());

                }
                layer.setReleaseType(mapLayer.getReleaseType());
                layer.setLazyLoad(mapLayer.getLazyLoad());
                layer.setServerName(mapLayer.getName());
                layer.setAlias(mapLayer.getAlias());
            }
            for (int i = 0; updateFlag && i < result.size(); i++) {
                MapLayer layer = result.get(i);
                String parentId = layer.getParentId();
                if (setParentId.containsKey(parentId)) {
                    layer.setParentId(setParentId.get(parentId));
                }
            }
            if (updateFlag) {
                List<String> ids = new ArrayList<>();
                ids.add(mapLayer.getId());
                // 更新服务的自图层前删除上一个服务的子图层
                mapLayerService.deleteChildAndField(ids);
            }
            R r = saveParseLayers(result, layerList, mapLayer.getParentId(), mapLayer.getOrgId(), updateFlag);
            Object data = r.getData();
            if (data != null) {
                List<MapLayer> resultData = (List<MapLayer>) data;
                result.clear();
                result.addAll(resultData);
            }
            mapLayerService.syncLayerName(result);
        }
        return true;
    }
}
